package com.scpii.universal.dispatch.tools;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import com.scpii.universal.concurrent.Callback;
import com.scpii.universal.dispatch.Const;
import com.scpii.universal.dispatch.Const.IniConfig;
import com.scpii.universal.exception.DownloadException;
import com.scpii.universal.io.img.Resize;

public class IosPicDownloadHandler extends PicDownloadHandler implements
		Callback {

	@Override
	public void downloadPic(String picFileDir, String fileName, String url)
			throws ClientProtocolException, IOException, Exception {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse response = null;
		try {
			response = client.execute(get);
		} catch (Exception e) {
			throw new DownloadException("请求URL资源出错，请查看url地址：" + url);
		}
		byte[] resData;
		if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String filePathSrc = picFileDir
						+ fileName.substring(0, fileName.lastIndexOf("."))
						+ IniConfig.PNG_2X_SUFIX;
				String filePathTarget = picFileDir + fileName;
				resData = EntityUtils.toByteArray(entity);
				Map<Object, Object> data = new HashMap<Object, Object>();
				data.put("filePathSrc", filePathSrc);
				data.put("filePathTarget", filePathTarget);

				// 等比例处理tab_press_bg.png，高度固定为49
				if ("tab_press_bg.png".equals(fileName)) {
					BufferedImage src = ImageIO.read(new ByteArrayInputStream(
							resData));
					int width = src.getWidth();
					int height = src.getHeight();
					width = (int) ((98.0 / height) * width);
					height = 98;
					Const.SIZE_MAP
							.put("tab_press_bg.png", width + "#" + height);
				}

				if ("Default.png".equals(fileName)) {
					scale4Iphone5(filePathTarget, resData);
					resData = process(resData, 640, 920);
				}

				if ("background.png".equals(fileName)) {
					resData = process(resData, 640, 920);
				}

				/**
				 * 修改内容： 处理圆角导航背景图片，压缩高度和其他不一致！约定圆角导航背景图的高度为118 修改人：左柳波
				 * 修改时间：2013-4-17
				 */
				if ("bg_tabbar.png".equals(fileName)) {
					BufferedImage src = ImageIO.read(new ByteArrayInputStream(
							resData));
					int height = src.getHeight();
					if (height > 146) {
						Const.SIZE_MAP.put("bg_tabbar.png", "640#118");
					}
				}
				String size = Const.SIZE_MAP.get(fileName);
				if (size != null) {
					resData = picCut(resData,
							Integer.parseInt(size.split("#")[0]),
							Integer.parseInt(size.split("#")[1]));
				}

				saveNomarlSizePic(filePathSrc, resData, this, data);
			}
		}
	}

	/**
	 * iphone 5 启动页面适配，新增图片"Default-568h@2x.png" 修改人：左柳波
	 * 
	 * @param filePathTarget
	 * @param filePathSrc
	 * @throws Exception
	 */
	private void scale4Iphone5(String filePathTarget, byte[] resData)
			throws Exception {
		String picName = filePathTarget.substring(filePathTarget
				.lastIndexOf("\\") + 1);
		if ("Default.png".equals(picName)) {
			filePathTarget = filePathTarget.substring(0,
					filePathTarget.lastIndexOf("\\"))
					+ "\\Default-568h@2x.png";
			BufferedImage bi = ImageIO.read(new ByteArrayInputStream(resData));
			byte[] image = process(bi, 640, 1096);

			File file = new File(filePathTarget);
			File parentFile = file.getParentFile();
			if (!parentFile.exists()) {
				parentFile.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			FileChannel fc = new RandomAccessFile(filePathTarget, "rw")
					.getChannel();
			fc.write(ByteBuffer.wrap(image));
			fc.close();
		}
	}

	private byte[] process(BufferedImage src, int destWidth, int destHeight)
			throws IOException {
		int srcWidth = src.getWidth();
		int srcHeight = src.getHeight();

		float widthRatio = (float) srcWidth / destWidth;
		float heightRatio = (float) srcHeight / destHeight;
		float ratio = 0.0f;
		if (widthRatio < heightRatio) {
			ratio = widthRatio;
		} else {
			ratio = heightRatio;
		}
		int width = (int) (srcWidth / ratio);
		int height = (int) (srcHeight / ratio);
		src = Resize.rize(src, width, height);
		src = src.getSubimage((width - destWidth) / 2,
				(height - destHeight) / 2, destWidth, destHeight);

		ByteArrayOutputStream out = new ByteArrayOutputStream();

		ImageIO.write(src, "png", out);
		return out.toByteArray();

	}

	private byte[] process(byte[] resData, int destWidth, int destHeight)
			throws IOException {
		BufferedImage src = ImageIO.read(new ByteArrayInputStream(resData));
		return process(src, destWidth, destHeight);
	}

	private byte[] picCut(byte[] resData, int width, int height)
			throws IOException {
		BufferedImage inImage = Resize.rize(
				ImageIO.read(new ByteArrayInputStream(resData)), width, height);
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		ImageIO.write(inImage, "png", outStream);
		resData = outStream.toByteArray();
		return resData;
	}

	@Override
	public boolean handleMessage(int action, Object... data) {
		return false;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean handleMessage(Object... data) {
		try {
			String filePathSrc = ((Map<String, String>) data[0])
					.get("filePathSrc");
			String filePathTarget = ((Map<String, String>) data[0])
					.get("filePathTarget");
			saveHalfSizePic(filePathTarget, filePathSrc);

			String picName = filePathTarget.substring(filePathTarget
					.lastIndexOf("\\") + 1);
			/**
			 * 修改内容：iphone 5 启动页面适配，新增图片"Default-568h@2x.png" 修改人：左柳波
			 * 修改时间：2013-1-6
			 * 
			 * 
			 * 
			 * if ("Default.png".equals(picName)) { filePathTarget =
			 * filePathTarget.substring(0, filePathTarget.lastIndexOf("\\")) +
			 * "\\Default-568h@2x.png"; BufferedImage bi = ImageIO.read(new
			 * File(filePathSrc)); byte[] image = process(bi, 640, 1096);
			 * 
			 * File file = new File(filePathTarget);
			 * Files.createParentDirs(file); if (!file.exists()) {
			 * file.createNewFile(); } FileChannel fc = new
			 * RandomAccessFile(filePathTarget, "rw").getChannel();
			 * fc.write(ByteBuffer.wrap(image)); fc.close();
			 * 
			 * }
			 */
			/**
			 * 修改内容：新增适配ipad版本logo "icon-144.png" 和 "icon-72.png" 修改人：左柳波
			 * 修改时间：2013-1-15
			 */
			if ("icon.png".equals(picName)) {
				String _filePathTarget = filePathTarget.substring(0,
						filePathTarget.lastIndexOf("\\")) + "\\icon-144.png";
				saveSpecificSizePic(_filePathTarget, filePathSrc, 144, 144);

				_filePathTarget = filePathTarget.substring(0,
						filePathTarget.lastIndexOf("\\"))
						+ "\\Icon-72@2x.png";
				saveSpecificSizePic(_filePathTarget, filePathSrc, 144, 144);

				_filePathTarget = filePathTarget.substring(0,
						filePathTarget.lastIndexOf("\\"))
						+ "\\icon-72.png";
				saveSpecificSizePic(_filePathTarget, filePathSrc, 72, 72);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

}